package com.sctvcloud.longchang.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridLayout;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.githang.statusbar.StatusBarCompat;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.longchang.R;
import com.sctvcloud.longchang.base.BaseFragment;
import com.sctvcloud.longchang.beans.FCityItem;
import com.sctvcloud.longchang.beans.FCityNews;
import com.sctvcloud.longchang.beans.FCityState;
import com.sctvcloud.longchang.beans.FocusColumn;
import com.sctvcloud.longchang.beans.LearnBean;
import com.sctvcloud.longchang.beans.LearnMainBean;
import com.sctvcloud.longchang.beans.LearnMainBeanNew;
import com.sctvcloud.longchang.beans.NewsItem;
import com.sctvcloud.longchang.beans.SubscriptionNoBean;
import com.sctvcloud.longchang.beans.SubscriptionNoTypeBean;
import com.sctvcloud.longchang.http.AbsListNetCallback;
import com.sctvcloud.longchang.http.AbsNetCallBack;
import com.sctvcloud.longchang.http.NetUtils;
import com.sctvcloud.longchang.ui.activities.ConvenientTelephoneActivity;
import com.sctvcloud.longchang.ui.activities.H5NormalActivity;
import com.sctvcloud.longchang.ui.activities.LoginActivity;
import com.sctvcloud.longchang.ui.adapter.GrideAdapter;
import com.sctvcloud.longchang.ui.adapter.GrideCankaoAdapter;
import com.sctvcloud.longchang.ui.adapter.SubscriptionNoAdapter;
import com.sctvcloud.longchang.ui.adapter.SubscriptionNoTypeAdapter;
import com.sctvcloud.longchang.ui.widget.NoScrollGridView;
import com.sctvcloud.longchang.utils.UserManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 更多订阅号
 */
public class MoreSubscriptionNoFragment extends BaseFragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener
        , SubscriptionNoTypeAdapter.OnTypeClickListener, SubscriptionNoAdapter.OnSubscriptionNoClickListener {

    @BindView(R.id.left_list)
    protected RecyclerView leftListRecyclerView;

    @BindView(R.id.gv_1)
    protected NoScrollGridView gv_1;

    @BindView(R.id.gv_2)
    protected NoScrollGridView gv_2;

    @BindView(R.id.title_1)
    protected TextView title_1;
    @BindView(R.id.title_2)
    protected TextView title_2;

    private String getSubscriptionNoTypeId;
    private SubscriptionNoTypeAdapter typeAdapter;
    private SubscriptionNoAdapter adapter;
    private boolean mIsLoading = false;
    private List<FocusColumn> subscriptionNoTypeList = new ArrayList<>();
    private List<SubscriptionNoTypeBean> typeList = new ArrayList<>();
    private List<SubscriptionNoBean> dataList = new ArrayList<>();
    private List<String> authorList = new ArrayList<>();
    private int currentTagIndex = 0;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_more_subscription_no, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //初始化请求栏目数据
        initView();

    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            StatusBarCompat.setStatusBarColor(getActivity(), getResources().getColor(R.color.white));

            subscriptionNoTypeList.clear();
            typeList.clear();
            dataList.clear();


            if (!TextUtils.isEmpty(HomeFragment.getPublic_url()))
                getSubscriptionNoTypeArray(HomeFragment.getPublic_url());
        }
    }

    private void initView() {
        leftListRecyclerView.setItemAnimator(new DefaultItemAnimator());
        leftListRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        //设置RecycleView显示的方向是水平还是垂直 GridLayout.HORIZONTAL水平  GridLayout.VERTICAL默认垂直
        gridLayoutManager.setOrientation(GridLayout.VERTICAL);
        //设置布局管理器， 参数gridLayoutManager对象

        subscriptionNoTypeList.clear();
        typeList.clear();
        dataList.clear();

        if (!TextUtils.isEmpty(HomeFragment.getPublic_url())) {
            getSubscriptionNoTypeArray(HomeFragment.getPublic_url());
        }
    }

    @Override
    public void onLoadMore() {

    }

    @Override
    public void onRefresh() {

    }

    /**
     * 获取 订阅号类型数据
     *
     * @param url
     */
    private void getSubscriptionNoTypeArray(String url) {


        NetUtils.getNetAdapter().getServiceData(getOwnerName(), url, new AbsNetCallBack<FCityItem>(FCityNews.class) {
            @Override
            public void onSuc(FCityItem fCityItem) {
                if (fCityItem != null && fCityItem.getInstitutionList() != null) {
                    List<FocusColumn> datas = transColumn(fCityItem.getInstitutionList());

                    if (ListUtils.isListValued(datas)) {
                        for (FocusColumn fc : datas) {
                            if (fc != null) {
                                switch (fc.getSubChannelType()) {
                                    case 0:
                                        subscriptionNoTypeList.add(fc);
                                        break;
                                }
                            }
                        }
                        getSubscriptionNoTypeArray();
                    } else {
                        toast("数据异常");
                    }

                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }

            @Override
            public void onEnd() {
                super.onEnd();

            }
        });


    }

    private void getSubscriptionNoTypeArray() {
        if (ListUtils.isListValued(subscriptionNoTypeList)) {
            for (FocusColumn fc : subscriptionNoTypeList) {
                if (fc != null) {
                    SubscriptionNoTypeBean bean = new SubscriptionNoTypeBean();
                    bean.setChannelId("" + fc.getChannelId());
                    bean.setChannelName(fc.getChannelName());
                    bean.setChannelUrl(fc.getChannelUrl());
                    bean.setChannelType(fc.getChannelType());
                    typeList.add(bean);
                }
            }
            initTypeData();
        } else {
            toast("数据异常");
        }

    }


    private void initTypeData() {
        if (null == adapter) {
            typeAdapter = new SubscriptionNoTypeAdapter(getActivity(), this);
            typeAdapter.setData(typeList);
            leftListRecyclerView.setAdapter(typeAdapter);
            typeAdapter.notifyDataSetChanged();
        }
        if (ListUtils.isListValued(typeList)) {
            for (int i = 0; i < typeList.size(); i++) {
                if (typeList.get(i).getChannelId().equalsIgnoreCase(getSubscriptionNoTypeId)) {
                    currentTagIndex = i;
                    typeList.get(i).setSelected(true);
                    dataList.clear();
                    getData(typeList.get(currentTagIndex).getChannelUrl());
                } else {
                    typeList.get(i).setSelected(false);
                }
            }


            OnTypeClick(0);

        }
    }

    @Override
    public void OnTypeClick(int position) {


        if (ListUtils.isListValued(typeList) && typeList.get(position).getChannelType()!=null && typeList.get(position).getChannelType().equals("1")) {
            Intent intent = new Intent(getActivity(), ConvenientTelephoneActivity.class);
            startActivity(intent);
            return;
        }

        //初始化数据

        mPageNo_one = 0;
        mPageAll_one = 0;
        serviceData.clear();

        mPageNo_two = 0;
        mPageAll_two = 0;
        cankaoData.clear();

        //初始化数据
        for (int i = 0; i < typeList.size(); i++) {
            if (i == position) {
                typeList.get(i).setSelected(true);
            } else {
                typeList.get(i).setSelected(false);
            }
        }
        typeAdapter.setData(typeList);
        //TODO 选择类型
        currentTagIndex = position;
        dataList.clear();
        if (ListUtils.isListValued(typeList.get(currentTagIndex).getSubscriptionNoList())) {
            dataList.addAll(typeList.get(currentTagIndex).getSubscriptionNoList());
            adapter.setData(dataList);
        } else {
            getLearnList(typeList.get(currentTagIndex).getChannelUrl());
        }



    }


    public List<FocusColumn> transColumn(List<FCityState> list) {

        List<FocusColumn> tar = new ArrayList<FocusColumn>();
        for (FCityState item : list) {
            FocusColumn tem = new FocusColumn();
            tem.setChannelName(item.getInstitutionName());
            tem.setChannelUrl(item.getInstitutionUrl());
            tem.setImage(item.getInstitutionImage());
            tem.setChannelType(item.getChannelType());
            tar.add(tem);
        }
        return tar;
    }


    private void getData(String url) {
        NetUtils.getNetAdapter().getLearnList(getOwnerName(), url, new AbsNetCallBack<LearnMainBeanNew>(LearnMainBeanNew.class) {
            @Override
            public void onSuc(LearnMainBeanNew newsItems) {
                if (null == newsItems) {
                    onError(null, null);
                    return;
                }


                if (ListUtils.isListValued(newsItems.getInstitutionList())) {
                    //    initData(newsItems.getInstitutionList());
                }

            }


            @Override
            public void onError(Throwable ex, String errorMsg) {

            }

            @Override
            public void onEnd() {

            }
        });

    }


    private List<LearnBean> learnNodeList;
    private List<NewsItem> serviceData = new ArrayList<NewsItem>();
    private List<NewsItem> cankaoData = new ArrayList<NewsItem>();


    private void getLearnList(String url) {


        NetUtils.getNetAdapter().getLearnListBean(getOwnerName(), url, new AbsNetCallBack<LearnMainBean>(LearnMainBean.class) {
            @Override
            public void onSuc(LearnMainBean newsItems) {
                if (null == newsItems) {
                    onError(null, null);
                    return;
                }

                gv1Adapter = new GrideAdapter(getActivity(), serviceData);
                gv_1.setAdapter(gv1Adapter);
                gv_1.setNumColumns(3);
                gv_1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        NewsItem item = serviceData.get(i);
                        if ("1".equalsIgnoreCase(item.getIsLogin())) {
                            if (null != UserManager.getInstance().getUser()) {
                                if ("1".equalsIgnoreCase(item.getIsConPhone())) {
                                    Intent intent = new Intent(getActivity(), ConvenientTelephoneActivity.class);
                                    startActivity(intent);
                                }else {

                                    if(item.getNewsTitle().equals("健康申报")){
                                        Intent intentNew = new Intent(getActivity(), H5NormalActivity.class);
                                        intentNew.putExtra(H5NormalActivity.EX_HTML,  item.getNewsUrl());
                                        intentNew.putExtra(H5NormalActivity.EX_TITLE, item.getNewsTitle());
                                        intentNew.putExtra(H5NormalActivity.IS_NEED_SHARE, false);
                                        startActivity(intentNew);
                                    }else {
                                        Intent intent = new Intent(getActivity(), H5NormalActivity.class);
                                        intent.putExtra(H5NormalActivity.EX_HTML, item.getNewsUrl());
                                        intent.putExtra(H5NormalActivity.EX_TITLE, item.getNewsTitle());
                                        intent.putExtra(H5NormalActivity.IS_NEED_PAY, true);
                                        String type = typeList.get(currentTagIndex).getChannelName();
                                        if ("活动专区".equalsIgnoreCase(type)) {
                                            intent.putExtra(H5NormalActivity.IS_NEED_SHARE, false);
                                        }
                                        startActivity(intent);
                                    }
                                }
                            } else {
                                toLogin();
                            }
                        } else if ("1".equalsIgnoreCase(item.getIsConPhone())) {
                            Intent intent = new Intent(getActivity(), ConvenientTelephoneActivity.class);
                            startActivity(intent);
                        } else {
                            if(item.getNewsTitle().equals("健康申报")){
                                Intent intentNew = new Intent(getActivity(), H5NormalActivity.class);
                                intentNew.putExtra(H5NormalActivity.EX_HTML,  item.getNewsUrl());
                                intentNew.putExtra(H5NormalActivity.EX_TITLE, item.getNewsTitle());
                                intentNew.putExtra(H5NormalActivity.IS_NEED_SHARE, false);
                                startActivity(intentNew);
                            }
                            else {
                                Intent intent = new Intent(getActivity(), H5NormalActivity.class);
                                intent.putExtra(H5NormalActivity.EX_HTML, item.getNewsUrl());
                                intent.putExtra(H5NormalActivity.EX_TITLE, item.getNewsTitle());
                                intent.putExtra(H5NormalActivity.IS_NEED_TOKEN, false);
                                intent.putExtra(H5NormalActivity.IS_NEED_PAY, true);
                                String type = typeList.get(currentTagIndex).getChannelName();
                                if ("活动专区".equalsIgnoreCase(type)) {
                                    intent.putExtra(H5NormalActivity.IS_NEED_SHARE, false);
                                }
                                startActivity(intent);
                            }
                        }
                    }
                });

                gv2Adapter = new GrideCankaoAdapter(getActivity(), cankaoData);
                gv_2.setAdapter(gv2Adapter);
                gv_2.setNumColumns(2);
                gv_2.setHorizontalSpacing(20);
                gv_2.setVerticalSpacing(16);
                gv_2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        NewsItem item = cankaoData.get(i);
                        if ("1".equalsIgnoreCase(item.getIsLogin())) {
                            if (null != UserManager.getInstance().getUser()) {
                                if(item.getNewsTitle().equals("健康申报")){
                                    Intent intentNew = new Intent(getActivity(), H5NormalActivity.class);
                                    intentNew.putExtra(H5NormalActivity.EX_HTML,  item.getNewsUrl());
                                    intentNew.putExtra(H5NormalActivity.EX_TITLE, item.getNewsTitle());
                                    intentNew.putExtra(H5NormalActivity.IS_NEED_SHARE, false);
                                    startActivity(intentNew);
                                }else {

                                    if ("1".equalsIgnoreCase(item.getIsConPhone())) {
                                        Intent intent = new Intent(getActivity(), ConvenientTelephoneActivity.class);
                                        startActivity(intent);
                                    } else {
                                        Intent intent = new Intent(getActivity(), H5NormalActivity.class);
                                        intent.putExtra(H5NormalActivity.EX_HTML, item.getNewsUrl());
                                        intent.putExtra(H5NormalActivity.EX_TITLE, item.getNewsTitle());
                                        intent.putExtra(H5NormalActivity.IS_NEED_PAY, true);
                                        String type = typeList.get(currentTagIndex).getChannelName();
                                        if ("活动专区".equalsIgnoreCase(type)) {
                                            intent.putExtra(H5NormalActivity.IS_NEED_SHARE, false);
                                        }
                                        startActivity(intent);
                                    }

                                }

                            } else {
                                toLogin();
                            }
                        } else if ("1".equalsIgnoreCase(item.getIsConPhone())) {
                            Intent intent = new Intent(getActivity(), ConvenientTelephoneActivity.class);
                            startActivity(intent);
                        } else {

                            if (item.getNewsTitle().equals("健康申报")) {
                                Intent intentNew = new Intent(getActivity(), H5NormalActivity.class);
                                intentNew.putExtra(H5NormalActivity.EX_HTML,  item.getNewsUrl());
                                intentNew.putExtra(H5NormalActivity.EX_TITLE, item.getNewsTitle());
                                intentNew.putExtra(H5NormalActivity.IS_NEED_SHARE, false);
                                startActivity(intentNew);
                            } else {
                                Intent intent = new Intent(getActivity(), H5NormalActivity.class);
                                intent.putExtra(H5NormalActivity.EX_HTML, item.getNewsUrl());
                                intent.putExtra(H5NormalActivity.EX_TITLE, item.getNewsTitle());
                                intent.putExtra(H5NormalActivity.IS_NEED_TOKEN, false);
                                intent.putExtra(H5NormalActivity.IS_NEED_PAY, true);
                                String type = typeList.get(currentTagIndex).getChannelName();
                                if ("活动专区".equalsIgnoreCase(type)) {
                                    intent.putExtra(H5NormalActivity.IS_NEED_SHARE, false);
                                }
                                startActivity(intent);
                            }
                        }

                    }
                });


                if (ListUtils.isListValued(newsItems.getLearnNodeList())) {

                    learnNodeList = newsItems.getLearnNodeList();
                    if (learnNodeList.size() == 1) {
                        //        getCommonDataOne(learnNodeList.get(0).getLearnNodeNewsListUrl());


                        serviceData.addAll(learnNodeList.get(0).getNodeNewsList());
                        gv1Adapter.notifyDataSetChanged();
                        setListViewHeightBasedOnChildren(gv_1, 3);
                        title_1.setText(learnNodeList.get(0).getLearnNodeName());
                        if(ListUtils.isListValued(serviceData)) {
                            title_1.setVisibility(View.VISIBLE);
                        }else{
                            title_1.setVisibility(View.GONE);
                        }
                        if(ListUtils.isListValued(cankaoData)) {
                            title_2.setVisibility(View.VISIBLE);
                        }else{
                            title_2.setVisibility(View.GONE);
                        }

                    } else if (learnNodeList.size() == 2) {

                        serviceData.addAll(learnNodeList.get(0).getNodeNewsList());
                        gv1Adapter.notifyDataSetChanged();
                        setListViewHeightBasedOnChildren(gv_1, 3);
                        title_1.setText(learnNodeList.get(0).getLearnNodeName());
                        if(ListUtils.isListValued(serviceData)) {
                            title_1.setVisibility(View.VISIBLE);
                        }else{
                            title_1.setVisibility(View.GONE);
                        }


                        cankaoData.addAll(learnNodeList.get(1).getNodeNewsList());
                        gv2Adapter.notifyDataSetChanged();
                        setListViewHeightBasedOnChildren(gv_2, 2);
                        title_2.setText(learnNodeList.get(1).getLearnNodeName());
                        if(ListUtils.isListValued(cankaoData)) {
                            title_2.setVisibility(View.VISIBLE);
                        }else{
                            title_2.setVisibility(View.GONE);
                        }

//                        getCommonDataOne(learnNodeList.get(0).getLearnNodeNewsListUrl());
//                        getCommonDataTwo(learnNodeList.get(1).getLearnNodeNewsListUrl());
                    } else {

                    }


                } else {
                    title_1.setVisibility(View.GONE);
                    title_2.setVisibility(View.GONE);

                }


            }


            @Override
            public void onError(Throwable ex, String errorMsg) {

            }

            @Override
            public void onEnd() {

            }
        });
    }

    private int mPageNo_one = 0;
    private int mPageAll_one = 0;
    private GrideAdapter gv1Adapter;


    private void getCommonDataOne(final String url) {
        NetUtils.getNetAdapter().getNewsPage(getOwnerName(), url, mPageNo_one, new AbsListNetCallback<NewsItem>(null) {
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                if (!ListUtils.isListValued(newsItems)) {
                    onError(null, null);
                    return;
                }

                serviceData.addAll(newsItems);

                if (mPageAll_one == 0) {
                    mPageAll_one = getPageResponse().getData().getPageAll();
                }

                if (mPageNo_one < mPageAll_one) {
                    mPageNo_one = mPageNo_one + 1;
                    if (mPageNo_one < mPageAll_one) {
                        getCommonDataOne(url);
                    }
                }
                gv1Adapter.notifyDataSetChanged();
                setListViewHeightBasedOnChildren(gv_1, 3);

            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                if (mPageNo_one > 0) {
                    mPageNo_one--;
                }
            }

            @Override
            public void onEnd() {

            }
        });
    }


    private int mPageNo_two = 0;
    private int mPageAll_two = 0;
    private GrideCankaoAdapter gv2Adapter;


    private void getCommonDataTwo(final String url) {
        NetUtils.getNetAdapter().getNewsPage(getOwnerName(), url, mPageNo_two, new AbsListNetCallback<NewsItem>(null) {
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                if (!ListUtils.isListValued(newsItems)) {
                    onError(null, null);
                    return;
                }

                cankaoData.addAll(newsItems);

                if (mPageAll_two == 0) {
                    mPageAll_two = getPageResponse().getData().getPageAll();
                }

                if (mPageNo_two < mPageAll_two) {
                    mPageNo_two = mPageNo_two + 1;
                    if (mPageNo_two < mPageAll_two) {
                        getCommonDataTwo(url);
                    }
                }
                gv2Adapter.notifyDataSetChanged();
                setListViewHeightBasedOnChildren(gv_2, 2);

            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                if (mPageNo_two > 0) {
                    mPageNo_two--;
                }
            }

            @Override
            public void onEnd() {

            }
        });
    }


    @Override
    public void OnSubscriptionNoClick(SubscriptionNoBean bean) {

    }


    public static void setListViewHeightBasedOnChildren(NoScrollGridView listView, int colum) {
        // 获取listview的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
        int col = colum;// listView.getNumColumns();
        int totalHeight = 0;
        // i每次加4，相当于listAdapter.getCount()小于等于4时 循环一次，计算一次item的高度，
        // listAdapter.getCount()小于等于8时计算两次高度相加
        for (int i = 0; i < listAdapter.getCount(); i += col) {
            // 获取listview的每一个item
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += listItem.getMeasuredHeight();
        }

        // 获取listview的布局参数
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // 设置高度
        params.height = totalHeight;
        // 设置margin
        ((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10);
        // 设置参数
        listView.setLayoutParams(params);
    }

    private void toLogin() {
        Intent intent = new Intent(getContext(), LoginActivity.class);
        startActivity(intent);
    }
}
